﻿#include "pch.h"
#include "Client.h"
#include "Server.h"

/**
 * 构造方法。
 * @param server    服务器
 */
Client::Client(Server* server): 
    mBuffer(NULL),
    mDataSize(0),
    mReceived(0),
    mServer(server) {
}

/**
 * 析构方法。
 */
Client::~Client() {
    if (mBuffer != NULL) {
        delete[] mBuffer;
    }
}

/**
 * 接收到数据的响应方法。
 * @param errorCode 错误码
 */
void Client::OnReceive(int errorCode) {
    if (mDataSize == 0) {
        // 接收数据长度
        CAsyncSocket::Receive(&mDataSize, sizeof(mDataSize));
        mBuffer = new char[mDataSize];
    } else {
        // 接收数据
        int read = CAsyncSocket::Receive(mBuffer + mReceived, mDataSize);
        if (read <= 0) {
            CAsyncSocket::OnReceive(errorCode);
            return;
        }
        mReceived += read;

        // 如果本次数据已全部接收完毕
        if (mReceived == mDataSize) {
            // 将数据转换成协议
            ImProtocol* pro = (ImProtocol*)mBuffer;

            // 处理协议
            CRITICAL_SECTION criticalSection = { 0 };
            InitializeCriticalSection(&criticalSection);
            EnterCriticalSection(&criticalSection);
            mServer->OnGetMessageFromClient(pro, this);
            LeaveCriticalSection(&criticalSection);

            // 重置成员变量
            mReceived = mDataSize = 0;
            delete[] mBuffer;
            mBuffer = NULL;
        }
    }

    CAsyncSocket::OnReceive(errorCode);
}
